<template>
	<view class="tab-bar">
		<view v-for="(item, index) in tabList" :key="index" class="tab-item" @tap="switchTab(item.path)">
			<image :src="currentPath === item.path ? item.selectedIcon : item.icon" class="tab-icon" mode="aspectFit">
			</image>
			<text :class="['tab-text', currentPath === item.path ? 'active' : '']">{{item.text}}</text>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'TabBar',
		data() {
			return {
				currentPath: '',
				tabList: [{
						text: '首页',
						path: '/pages/index/index',
						icon: '/static/tabbar/home.png',
						selectedIcon: '/static/tabbar/home-active.png'
					},
					{
						text: '扫一扫',
						path: 'scan',
						icon: '/static/tabbar/scan.png',
						selectedIcon: '/static/tabbar/scan-active.png'
					},
					{
						text: '我的',
						path: '/pages/mine/mine',
						icon: '/static/tabbar/mine.png',
						selectedIcon: '/static/tabbar/mine-active.png'
					}
				]
			}
		},
		created() {
			// 获取当前页面路径
			this.updateCurrentPath();
			// 添加页面显示的监听
			uni.$on('updateTabBar', () => {
				this.updateCurrentPath();
			});
		},
		onShow() {
			// 页面显示时检查是否有存储的当前Tab路径
			try {
				const storedPath = uni.getStorageSync('currentTabPath');
				if (storedPath) {
					this.currentPath = storedPath;
					// 使用后清除，避免影响其他操作
					uni.removeStorageSync('currentTabPath');
				} else {
					// 没有存储的路径，正常更新
					this.updateCurrentPath();
				}
			} catch (e) {
				console.error('读取存储的Tab路径失败:', e);
				this.updateCurrentPath();
			}
		},
		beforeDestroy() {
			// 移除监听，防止内存泄漏
			uni.$off('updateTabBar');
		},
		methods: {
			updateCurrentPath() {
				const pages = getCurrentPages();
				if (pages.length > 0) {
					const currentPage = pages[pages.length - 1];
					this.currentPath = `/${currentPage.route}`;
					console.log('TabBar当前路径更新为:', this.currentPath);
				}
			},
			switchTab(path) {
				if (this.currentPath === path) return;
				
				// 处理扫一扫的特殊情况
				if (path === 'scan') {
					this.scanCode();
					return;
				}
				
				uni.switchTab({
					url: path,
					success: () => {
						this.currentPath = path;
						uni.$emit('updateTabBar');
					}
				});
			},
			
			scanCode() {
				uni.scanCode({
					onlyFromCamera: false, // 允许从相册选择图片
					scanType: ['qrCode'], // 只扫描二维码
					success: (res) => {
						console.log('扫码结果:', res);
						
						if (res.result) {
							try {
								// 处理扫码结果
								this.handleScanResult(res.result);
							} catch (error) {
								console.error('处理扫码结果出错:', error);
								uni.showToast({
									title: '无效的二维码',
									icon: 'none'
								});
							}
						} else {
							uni.showToast({
								title: '未获取到有效的二维码内容',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('扫码失败:', err);
						// 用户取消扫码不提示
						if (err.errMsg !== 'scanCode:fail cancel') {
							uni.showToast({
								title: '扫描失败，请重试',
								icon: 'none'
							});
						}
					}
				});
			},
			handleScanResult(result) {
				console.log('处理扫码结果:', result);
				
				// 判断扫码结果类型
				if (result.startsWith('http') || result.startsWith('https')) {
					// 网址类型
					uni.showModal({
						title: '提示',
						content: '是否打开链接: ' + result,
						success: (res) => {
							if (res.confirm) {
								// 在小程序中可以通过web-view组件打开网页
								uni.navigateTo({
									url: `/pages/webview/webview?url=${encodeURIComponent(result)}`
								});
							}
						}
					});
				} else if (result.includes('pile_id=')) {
					// 充电桩二维码
					try {
						// 解析充电桩ID
						const pileId = this.getQueryString(result, 'pile_id');
						if (pileId) {
							// 保存充电桩ID到Vuex
							this.$store.dispatch('charger/setPileId', pileId);
							
							uni.showToast({
								title: '扫描到充电桩ID: ' + pileId,
								icon: 'none'
							});
							
							// 跳转到开始充电页面
							uni.navigateTo({
								url: `/pages/start_charging/startCharging?pileId=${pileId}`
							});
						} else {
							uni.showToast({
								title: '无效的充电桩信息',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('解析充电桩ID失败:', error);
						uni.showToast({
							title: '无效的充电桩二维码',
							icon: 'none'
						});
					}
				} else {
					// 其他类型的二维码
					uni.showModal({
						title: '二维码内容',
						content: result,
						showCancel: false
					});
				}
			},
			// 从URL中获取参数值
			getQueryString(url, name) {
				const reg = new RegExp(`(^|&|\\?|\\/)${name}=([^&]*)(&|$)`, 'i');
				const r = url.match(reg);
				if (r != null) {
					return decodeURIComponent(r[2]);
				}
				return null;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background: #FFFFFF;
		display: flex;
		padding-bottom: env(safe-area-inset-bottom);
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

		.tab-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 5rpx 0;

			.tab-icon {
				width: 48rpx;
				height: 48rpx;
				margin-bottom: 4rpx;
			}

			.tab-text {
				font-size: 24rpx;
				color: #666;

				&.active {
					color: #1989fa;
				}
			}
		}
	}
</style>